package main

import (
	"fmt"
	"net/http"
	"github.com/gorilla/mux"
)

func main() {
	r := mux.NewRouter()

	r.HandleFunc("/", finalHandler)
	r.Use(loggingMiddleware)
	r.Use(secMiddleware)
 
	http.ListenAndServe(":8080", r)
}

func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		//Do stuff here
		fmt.Println("loggingMiddleware is running")
		fmt.Fprintf(w, "Here is MiddleWare: request url is : %s\r\n", r.URL)
		// 执行下一个 Handler,可以是另一个中间件,或者是最终的 Handler
		// 此处执行SecMiddleware Handler
		next.ServeHTTP(w, r)
	})
}
 
func secMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("secMiddleware is running")
		//Do stuff here
		fmt.Fprintf(w, "Here is Second MiddleWare: request url is : %s\r\n", r.URL)
		// 执行下一个 Handler,可以是另一个中间件,或者是最终的 Handler
		// 此处执行finalHandler
		next.ServeHTTP(w, r)
	})
}
func finalHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("finalHandler is running")
	w.Write([]byte("Here is Handler"))
}
